<?php
namespace app\command;

use app\beautiful\model\finance\AccountBalanceModel;
use app\beautiful\model\finance\SettlementModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberLockModel;
use app\beautiful\model\order\BuyOrderModel;
use app\beautiful\model\order\GoodsOrderItemModel;
use app\beautiful\model\partner\PartnerCommissionModel;
use app\beautiful\model\PartnerModel;
use app\beautiful\model\setting\ConsumeBonusSettingModel;
use app\beautiful\model\setting\PartnerBonusSettingModel;
use app\beautiful\model\setting\PartnerPromotionSettingModel;
use app\common\model\DataConfigModel;
use app\common\model\MemberMoneyDetailModel;
use app\common\model\OrderSettleModel;
use app\common\model\ShopBalanceLogsModel;
use app\common\model\ShopDetailModel;
use app\common\model\ShopModel;
use app\stores\model\order\GoodsOrderModel;
use app\stores\model\promotion\PromotionmoneydetailModel;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class Ordersettle extends Command
{
    public $settle_data;
    protected function configure()
    {
        $this->setName('Ordersettle')
            ->addArgument('name', Argument::OPTIONAL, "your name")
            ->addOption('city', null, Option::VALUE_REQUIRED, 'city name')
            ->setDescription('Say Hello');
    }

    protected function execute(Input $input, Output $output)
    {
        $h=date('H');
        $i=date('i');
        $name = trim($input->getArgument('name'));
        if(($h!='00' || $i!='05') && empty($name)){
            $output->writeln("暂不能执行！每天凌晨05分执行" );exit();
        }
        $page=1;
        $num=10;
        //获取当天的开始和结束时间
        $day_start=strtotime(date('Y-m-d 00:00:00',strtotime('-1 day')));
        $day_end=strtotime(date('Y-m-d 23:59:59',strtotime('-1 day')));
        $consume=new ConsumeBonusSettingModel();
        $partnerbonus=new PartnerBonusSettingModel();
        $ShopBalanceLogs=new ShopBalanceLogsModel();
        $MemberMoneyDetail=new MemberMoneyDetailModel();
        $PromotionmoneydetailModel=new PromotionmoneydetailModel();
        $ShopDetail=new ShopDetailModel();
        $ShopModel=new ShopModel();
        //处理下单
        $order['a.edit_time']='asc';
        $order['a.order_id']='asc';
        $s=[];
        $s['status']=8;
        $s['is_settle']=0;
        $s['is_all']=1;
        $s['is_paid']=1;
        if(!empty($name) && $name!=1){
            $s['shop_id']=$name;
        }
        $s['>=edit_time']=$day_start;
        $s['<=edit_time']=$day_end;
        $list=GoodsOrderModel::list($s,$order,$page,$num);
        if(!empty($list)){
            foreach ($list as $v){
                $shop_id=$v['shop_id'];
                $v['need_pay']=$v['need_pay']-$v['refund_money'];
                $order_settle['settle_time']=date('Y-m-d',$day_start);
                $order_settle['shop_id']=$shop_id;
                $order_settle['order_id']=$v['order_id'];
                $order_settle['service_money']=0;
                $order_settle['settle_money']=$v['need_pay'];
                if($v['mix_pay_type']==''){
                    if($v['pay_type']=='money'){//储值卡支付不参与结算
                        $order_settle['settle_money']=0;
                    }
                }else{
                    $order_settle['settle_money']=0;
                    $pay_type=explode(',',$v['mix_pay_type']);
                    $v['mix_pay_type']=$pay_type;
                    foreach ($pay_type as $pay){
                        if($pay!='money'){
                            $order_settle['settle_money']+=$v[$pay];
                        }
                    }
                    $order_settle['settle_money']=$order_settle['settle_money']-$v['refund_money'];
                }
                $s=[];
                $s['shop_id']=$shop_id;
                $n_shop_detail=$ShopDetail->where($s)->find();
                $n_shop=$ShopModel->where($s)->find();
                $buckle_money=0;
                $no_settle_type=['flash_sale','pin_tuan','set_meal'];
                //计算消费奖励
                $s=[];
                $s['shop_id']=$shop_id;
                $s['is_open']=1;
                $consume_money=0;
                $partner_bonus=0;
                $shop_set=$consume->where($s)->find();
                if(!empty($shop_set) && !in_array($v['order_type'],$no_settle_type)){
                    if($shop_set['bonus_budget_type']==1){
                        $consume_money=$v['need_pay']*($shop_set['bonus_budget']/100);
                    }elseif ($shop_set['bonus_budget_type']==2){
                        $consume_money=$v['all_goods_gross']*($shop_set['normal_bonus_budget']/100);
                    }
                }
                $order_settle['consume_money']=$consume_money;
                $v['consume_money']=$consume_money;
                //计算合伙人奖励
                $s=[];
                $s['shop_id']=$shop_id;
                $s['is_delete']=0;
                $shop_set_partner=$partnerbonus->where($s)->find();
                if(!empty($shop_set_partner) && $n_shop_detail['is_open_partner_manage']==1 && !in_array($v['order_type'],$no_settle_type)){
                    if($shop_set_partner['bonus_budget_type']==1){
                        $partner_bonus=$v['need_pay']*($shop_set_partner['bonus_budget']/100);
                    }elseif ($shop_set_partner['bonus_budget_type']==2){
                        $partner_bonus=$v['all_goods_gross']*($shop_set_partner['normal_bonus_budget']/100);
                    }
                }
                $order_settle['partner_bonus']=$partner_bonus;
                $v['partner_bonus']=$partner_bonus;
                //锁客奖励
                $lock_money=0;
                if($n_shop['is_lock']==1){
                    $lock_list=$ShopBalanceLogs->where(['order_id'=>$v['order_id'],'status'=>0,'balance_type'=>1])->select()->toArray();
                    if(!empty($lock_list)){
                        foreach ($lock_list as $lc_v){
                            $lock_money+=$lc_v['balance'];
                            ShopBalanceLogsModel::in($lc_v['balance'], 1, $lc_v['shop_id'], $v['order_id'], 1,1,'lock_money');
                        }
                    }
                }
                $order_settle['lock_money']=$lock_money;
                $v['lock_money']=$lock_money;
                //股东推广提成
                $promotion_money=0;
                $s=[];
                $s['type']=4;
                $s['g_order_id']=$v['order_id'];
                $s['money_status']=0;
                $promotion_info=$MemberMoneyDetail->where($s)->find();
                if(!empty($promotion_info) && $n_shop_detail['is_open_partner_dividend']==1 && !in_array($v['order_type'],$no_settle_type)){
                    $shop_detail=ShopDetailModel::where(['shop_id'=>$promotion_info['shop_id'],'is_open_partner_manage'=>1])->find();
                    if(!empty($shop_detail)){
                        $promotion_money=$promotion_info['money'];
                        MemberMoneyDetailModel::in($promotion_info['money'],1,4,$promotion_info['shop_id'],$promotion_info['member_id'],$promotion_info['partner_id'],$v['order_id'],$order_type=0,$money_status=1);
                    }
                }
                //地推推广提成
                $s=[];
                $s['type']=1;
                $s['order_id']=$v['order_id'];
                $s['team_id']=$v['team_id'];
                $promotion_money1=$PromotionmoneydetailModel->where($s)->sum('money');
                $promotion_money+=$promotion_money1;
                $order_settle['promotion_money']=$promotion_money;
                $v['promotion_money']=$promotion_money;
                $buckle_money=$promotion_money+$lock_money+$consume_money+$partner_bonus;
                $order_settle['buckle_money']=$buckle_money;
                $order_settle['settle_money']=$order_settle['settle_money']-$buckle_money;
                $this->init_data($v);//格式化数据
                $res=OrderSettleModel::insertGetId($order_settle);
                if(!empty($res)){
                    GoodsOrderModel::update(['is_settle'=>1],['order_id'=>$v['order_id']]);
                }
            }
        }
        //处理买单
        $order=[];
        $order['a.edit_time']='asc';
        $order['a.buy_order_id']='asc';
        $s=[];
        $s['status']=1;
        $s['is_settle']=0;
        $s['is_all']=1;
        $s['is_paid']=1;
        if(!empty($name) && $name!=1){
            $s['shop_id']=$name;
        }
        $s['>=edit_time']=$day_start;
        $s['<=edit_time']=$day_end;
        $list=BuyOrderModel::list($s,$order,$page,$num);
        if(!empty($list)){
            $config=DataConfigModel::where(['id'=>1])->find();
            foreach ($list as $v){
                $shop_id=$v['shop_id'];
                $v['pay_money']=$v['pay_money']-$v['refund_money'];
                $order_settle=[];
                $order_settle['settle_time']=date('Y-m-d',$day_start);
                $order_settle['shop_id']=$shop_id;
                $order_settle['b_order_id']=$v['buy_order_id'];
                $order_settle['service_money']=0;
                $order_settle['settle_money']=$v['pay_money'];
                if($v['mix_pay_type']==''){
                    if($v['pay_type']=='money'){//储值卡支付不参与结算
                        $order_settle['settle_money']=0;
                    }
                }else{
                    $order_settle['settle_money']=0;
                    $pay_type=explode(',',$v['mix_pay_type']);
                    $v['mix_pay_type']=$pay_type;
                    foreach ($pay_type as $pay){
                        if($pay!='money'){
                            $order_settle['settle_money']+=$v[$pay];
                        }
                    }
                    $order_settle['settle_money']=$order_settle['settle_money']-$v['refund_money'];
                }
                $s=[];
                $s['shop_id']=$shop_id;
                $n_shop_detail=$ShopDetail->where($s)->find();
                $n_shop=$ShopModel->where($s)->find();
                $buckle_money=0;
                //计算消费奖励
                $s=[];
                $s['shop_id']=$shop_id;
                $s['is_open']=1;
                $consume_money=0;
                $partner_bonus=0;
                $shop_set=$consume->where($s)->find();
                if(!empty($shop_set)){
                    if($shop_set['bonus_budget_type']==1){
                        $consume_money=$v['pay_money']*($shop_set['bonus_budget']/100);
                    }elseif ($shop_set['bonus_budget_type']==2){
                        $consume_money=$v['pay_money']*($shop_set['buy_bonus_budget']/100);
                    }
                }
                $order_settle['consume_money']=$consume_money;
                $v['consume_money']=$consume_money;
                //计算合伙人奖励
                $s=[];
                $s['shop_id']=$shop_id;
                $s['is_delete']=0;
                $shop_set_partner=$partnerbonus->where($s)->find();
                if(!empty($shop_set_partner) && $n_shop_detail['is_open_partner_manage']==1){
                    if($shop_set_partner['bonus_budget_type']==1){
                        $partner_bonus=$v['pay_money']*($shop_set_partner['bonus_budget']/100);
                    }elseif ($shop_set_partner['bonus_budget_type']==2){
                        $partner_bonus=$v['pay_money']*($shop_set_partner['buy_bonus_budget']/100);
                    }
                }
                $order_settle['partner_bonus']=$partner_bonus;
                $v['partner_bonus']=$partner_bonus;
                //锁客奖励
                $lock_money=0;
                if($n_shop['is_lock']==1){
                    memberlock($v['buy_order_id'],2);//锁客分红
                    $lock_money=0;
                    $lock_list=$ShopBalanceLogs->where(['b_order_id'=>$v['buy_order_id'],'status'=>0,'balance_type'=>1])->select()->toArray();
                    if(!empty($lock_list)){
                        if($config['is_lock']!=0){//锁客分红开启
                            $member_id=$v['member_id'];
                            $n_lock_money=round($v['pay_money']*$config['lock_ratio']/100,2);
                            foreach ($lock_list as $lc_v){
                                $lock_info=MemberLockModel::where(['member_id'=>$member_id,'shop_id'=>$lc_v['shop_id']])->find();
                                if(!empty($lock_info)){
                                    $balance=round($n_lock_money*$lock_info['share_ratio']/100,2);
                                    $lock_money+=$balance;
                                    ShopBalanceLogsModel::in($balance, 1, $lc_v['shop_id'], $v['buy_order_id'], 2,1,'lock_money');
                                }
                            }
                        }else{//锁客分红关闭
                            foreach ($lock_list as $lc_v){
                                $lc_v['balance']=0;
                                $lock_money+=$lc_v['balance'];
                                ShopBalanceLogsModel::in($lc_v['balance'], 1, $lc_v['shop_id'], $v['buy_order_id'], 2,1,'lock_money');
                            }
                        }
                    }
                }
                $order_settle['lock_money']=$lock_money;
                $v['lock_money']=$lock_money;
                //股东推广提成
                $promotion_money=0;
                $s=[];
                $s['type']=4;
                $s['b_order_id']=$v['buy_order_id'];
                $s['money_status']=0;
                $promotion_info=$MemberMoneyDetail->where($s)->find();
                if(!empty($promotion_info) && $n_shop_detail['is_open_partner_dividend']==1 ){
                    $shop_detail=ShopDetailModel::where(['shop_id'=>$promotion_info['shop_id'],'is_open_partner_manage'=>1])->find();
                    if(!empty($shop_detail)){
                        $where=[];
                        $where['shop_id']=$shop_id;
                        $where['member_id']=$promotion_info['member_id'];
                        $partner_info=PartnerModel::info($where,[]);
                        $setting=PartnerPromotionSettingModel::where(['shop_id'=>$shop_id,'is_delete'=>0])->find();
                        $commission=0;
                        if(!empty($partner_info) && !empty($setting)){
                            if($setting['dividend_type']==1){//订单金额
                                $commission=round($v['pay_money']*($partner_info['ratio']/100),2);
                            }elseif ($setting['dividend_type']==2){//按毛利分成
                                $commission=round($v['pay_money']*($partner_info['buy_ratio']/100),2);
                            }
                            $promotion_money=$commission;
                        }
                        MemberMoneyDetailModel::in($commission,1,4,$promotion_info['shop_id'],$promotion_info['member_id'],$promotion_info['partner_id'],$v['buy_order_id'],$order_type=1,$money_status=1);
                        $up_commission=[];
                        $up_commission['commission']=$commission;
                        $up_commission['monetary']=$v['pay_money'];
                        PartnerCommissionModel::update(['order_id'=>$v['buy_order_id'],'type'=>'买单订单','partner_id'=>$promotion_info['partner_id']],$up_commission);
                    }
                }
                $order_settle['promotion_money']=$promotion_money;
                $v['promotion_money']=$promotion_money;
                $buckle_money=$promotion_money+$lock_money+$consume_money+$partner_bonus;
                $order_settle['buckle_money']=$buckle_money;
                $order_settle['settle_money']=$order_settle['settle_money']-$buckle_money;
                $this->init_data($v,2);//格式化数据
                $b_res=OrderSettleModel::insertGetId($order_settle);
                if(!empty($b_res)){
                    BuyOrderModel::update(['is_settle'=>1],['buy_order_id'=>$v['buy_order_id']]);
                }
            }
        }
        $this->insert_settle();
        $output->writeln("end");exit();
    }
    public function init_data($data,$type=1){
        $shop_id=$data['shop_id'];
        if($type==2){
            $data['need_pay']=$data['pay_money'];
        }
        if(empty($this->settle_data[$shop_id])){
            $this->settle_data[$shop_id]['shop_id']=$shop_id;
            $this->settle_data[$shop_id]['order_pay_price']=0;
            $this->settle_data[$shop_id]['settlement_price']=0;
            $this->settle_data[$shop_id]['order_count']=0;
            $this->settle_data[$shop_id]['order_count_detail']['cashier_order_count']=0;
            $this->settle_data[$shop_id]['order_count_detail']['order_count']=0;
            $this->settle_data[$shop_id]['order_count_detail']['write_off_order_count']=0;
            $this->settle_data[$shop_id]['order_count_detail']['refund_order_count']=0;
            $this->settle_data[$shop_id]['pay_detail']['juhe']=0;
            $this->settle_data[$shop_id]['pay_detail']['weixin']=0;
            $this->settle_data[$shop_id]['pay_detail']['alipay']=0;
            $this->settle_data[$shop_id]['pay_detail']['money']=0;
            $this->settle_data[$shop_id]['pay_detail']['offline']=0;
            $this->settle_data[$shop_id]['pay_detail']['other']=0;
            $this->settle_data[$shop_id]['pay_detail']['platform_money']=0;
            $this->settle_data[$shop_id]['deduct_price']=0;
            $this->settle_data[$shop_id]['deduct_detail']['service_price']=0;
            $this->settle_data[$shop_id]['deduct_detail']['lock_price']=0;
            $this->settle_data[$shop_id]['deduct_detail']['bonus_price']=0;
            $this->settle_data[$shop_id]['deduct_detail']['promotion_price']=0;
            $this->settle_data[$shop_id]['deduct_detail']['consume_price']=0;
            $this->settle_data[$shop_id]['deduct_detail']['other_price']=0;
            $this->settle_data[$shop_id]['coupon_price']=0;
            $this->settle_data[$shop_id]['coupon_detail']=[];
            $this->settle_data[$shop_id]['write_off_price']=0;
            $this->settle_data[$shop_id]['write_off_detail']=[];
            $this->settle_data[$shop_id]['status']=1;
            $this->settle_data[$shop_id]['settlement_time']=date('Y-m-d',strtotime('-1 day'));
            $this->settle_data[$shop_id]['add_time']=date('Y-m-d H:i:s');
        }
        $deduct_price=$data['lock_money']+$data['partner_bonus']+$data['promotion_money']+$data['consume_money'];
        $settlement_price=0;
        $this->settle_data[$shop_id]['order_pay_price']+=$data['need_pay'];
        $this->settle_data[$shop_id]['coupon_price']+=$data['coupon_money'];
        $this->settle_data[$shop_id]['order_count']+=1;
        $this->settle_data[$shop_id]['deduct_price']+=$deduct_price;
        $this->settle_data[$shop_id]['order_count_detail']['order_count']+=1;
        $this->settle_data[$shop_id]['deduct_detail']['lock_price']+=$data['lock_money'];
        $this->settle_data[$shop_id]['deduct_detail']['bonus_price']+=$data['partner_bonus'];
        $this->settle_data[$shop_id]['deduct_detail']['promotion_price']+=$data['promotion_money'];
        $this->settle_data[$shop_id]['deduct_detail']['consume_price']+=$data['consume_money'];
        if(empty($data['mix_pay_type'])){
            if($data['pay_type']=='platform_money'){//平台钱包
                $this->settle_data[$shop_id]['pay_detail']['platform_money']+=$data['need_pay'];
                $settlement_price=$data['need_pay'];
            }
            if($data['pay_type']=='weixin'){//微信
                $this->settle_data[$shop_id]['pay_detail']['weixin']+=$data['need_pay'];
                $settlement_price=$data['need_pay'];
            }
            if($data['pay_type']=='money'){//储值卡
                $this->settle_data[$shop_id]['pay_detail']['money']+=$data['need_pay'];
            }
        }else{
            foreach ($data['mix_pay_type'] as $pay){
                $this->settle_data[$shop_id]['pay_detail'][$pay]+=$data[$pay];
                if($pay!='money'){
                    $settlement_price+=$data[$pay];
                }
            }
            $settlement_price=$settlement_price-$data['refund_money'];
        }
        $this->settle_data[$shop_id]['settlement_price']+=($settlement_price-$deduct_price);
        //统计优惠券
        if(!empty($data['member_coupon_id'])){
            $coupon=MemberCouponModel::where(['member_coupon_id'=>$data['member_coupon_id']])->find();
            if(!empty($coupon)){
                if(empty($this->settle_data[$shop_id]['coupon_detail'][$coupon['coupon_id']])){
                    $this->settle_data[$shop_id]['coupon_detail'][$coupon['coupon_id']]['name']=$coupon['name'];
                    $this->settle_data[$shop_id]['coupon_detail'][$coupon['coupon_id']]['coupon_money']=$coupon['coupon_money'];
                    $this->settle_data[$shop_id]['coupon_detail'][$coupon['coupon_id']]['num']=1;
                }else{
                    $this->settle_data[$shop_id]['coupon_detail'][$coupon['coupon_id']]['num']+=1;
                }
            }
        }
        //统计套餐
        if($type==1){
            $order_item=GoodsOrderItemModel::where(['order_id'=>$data['order_id'],'type'=>3])->find();
            if(!empty($order_item)){
                $this->settle_data[$shop_id]['order_count_detail']['write_off_order_count']+=1;
                $this->settle_data[$shop_id]['write_off_price']+=$data['need_pay'];
                if(empty($this->settle_data[$shop_id]['write_off_detail'][$order_item['goods_id']])){
                    $this->settle_data[$shop_id]['write_off_detail'][$order_item['goods_id']]['goods_name']=$order_item['goods_name'];
                    $this->settle_data[$shop_id]['write_off_detail'][$order_item['goods_id']]['goods_price']=$order_item['goods_price'];
                    $this->settle_data[$shop_id]['write_off_detail'][$order_item['goods_id']]['goods_num']=$order_item['goods_num'];
                }else{
                    $this->settle_data[$shop_id]['write_off_detail'][$order_item['goods_id']]['goods_num']+=$order_item['goods_num'];
                }
            }
        }
    }
    public function insert_settle(){
        if(!empty($this->settle_data)){
            foreach ($this->settle_data as $shop_id=>$v){
                $insert=$v;
                $insert['order_count_detail']=json_encode($v['order_count_detail']);
                $insert['pay_detail']=json_encode($v['pay_detail']);
                $insert['deduct_detail']=json_encode($v['deduct_detail']);
                $insert['coupon_detail']=json_encode($v['coupon_detail']);
                $insert['write_off_detail']=json_encode($v['write_off_detail']);
                $s=[];
                $s['shop_id']=$shop_id;
                $s['settle_time']=$v['settlement_time'];
                $settle_id=SettlementModel::insertGetId($insert);
                if(!empty($settle_id)){
                    OrderSettleModel::update(['settle_id'=>$settle_id],$s);
                    $settlement_price=$insert['settlement_price'];
                    if($settlement_price>0){//结算金额大于0
                        ShopBalanceLogsModel::in($settlement_price, 1, $shop_id, 0, 3,1);
                    }elseif($settlement_price<0){
                        $AccountBalanceModel=new AccountBalanceModel();
                        $account_info=$AccountBalanceModel->where(['shop_id'=>$shop_id,'is_delete'=>0])->find();
                        $settlement_price=abs($settlement_price);
//                        if($account_info['account_money']>=$settlement_price){
                            ShopBalanceLogsModel::in($settlement_price, -1, $shop_id, 0, 3,1);
//                        }else{
//                            if($account_info['account_money']>0){
//                                ShopBalanceLogsModel::in($account_info['account_money'], -1, $shop_id, 0, 3,1);
//                                $cha_money=$settlement_price-$account_info['account_money'];
//                                $insert=[];
//                                $insert['shop_id']=$shop_id;
//                                $insert['type']=-1;
//                                $insert['status']=1;
//                                $insert['balance_type']=2;
//                                $insert['from_type']=2;
//                                $insert['before_balance']=$account_info['spare_money'];
//                                $insert['balance']=$cha_money;
//                                $insert['balance']='-'.$cha_money;
//                                $insert['after_balance']=($account_info['spare_money']-$cha_money);
//                                $insert['settle_time']=date('Y-m-d',strtotime('-1 day'));
//                                $insert['add_time']=date('Y-m-d H:i:s');
//                                $res=ShopBalanceLogsModel::insertGetId($insert);
//                                $AccountBalanceModel->n_dec(['shop_id'=>$shop_id],'spare_money',$cha_money);
//                            }else{
//                                ShopBalanceLogsModel::in($settlement_price, -1, $shop_id, 0, 3,1,'spare_money');
//                            }
//                        }
                    }
                }
            }
        }
    }
}